package com.ethannhu.todaynews.component.main

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import androidx.core.view.GravityCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.angcyo.tablayout.delegate2.ViewPager2Delegate
import com.ethannhu.superui.dialog.SuperDialog
import com.ethannhu.superui.extension.hide
import com.ethannhu.superui.extension.shortToast
import com.ethannhu.superui.extension.show
import com.ethannhu.superui.process.SuperProcessUtil
import com.ethannhu.todaynews.AppContext
import com.ethannhu.todaynews.R
import com.ethannhu.todaynews.activity.BaseViewModelActivity
import com.ethannhu.todaynews.component.ad.Ad
import com.ethannhu.todaynews.component.login.LoginHomeActivity
import com.ethannhu.todaynews.component.login.LoginViewModel
import com.ethannhu.todaynews.component.user.User
import com.ethannhu.todaynews.component.userdetail.UserDetailActivity
import com.ethannhu.todaynews.component.web.WebActivity
import com.ethannhu.todaynews.databinding.ActivityMainBinding
import com.ethannhu.todaynews.databinding.ItemTabBinding
import com.ethannhu.todaynews.util.Constant
import com.ethannhu.todaynews.util.ImageUtil
import com.ethannhu.todaynews.util.PreferenceUtil
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.net.URI

/**
 * 首页
 */
class MainActivity : BaseViewModelActivity<ActivityMainBinding>() {
    //不设置沉浸式模式偏移，让子 Fragment 自行设置
    override val enableInset: Boolean = false
    private lateinit var viewModel: MainViewModel

    companion object {
        /**
         * 底部指示器（tab）文本，图标，选中的图标
         */
        private val indicatorTitles = intArrayOf(
            R.string.discovery,
            R.string.video,
            R.string.category,
            R.string.me
        )
        private val indicatorIcons = intArrayOf(
            R.drawable.selector_tab_discovery,
            R.drawable.selector_tab_video,
            R.drawable.selector_tab_category,
            R.drawable.selector_tab_me
        )

    }

    override fun initData() {
        super.initData()
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        initViewModel(viewModel)

        lifecycleScope.launch {
            viewModel.userData.collect {
                showUserData(it)
            }
        }


        val action = intent.action
        if (Constant.ACTION_LOGIN == action) {
            //跳转到登录界面
            startActivity(LoginHomeActivity::class.java)
        } else if (Constant.ACTION_AD == action) {
            //广告点击
            processAdClick(intent.getParcelableExtra(Constant.AD)!!)
        }


        // viewpager2设置
        binding.content.pager.apply {
            offscreenPageLimit = indicatorTitles.size
            adapter = MainAdapter(this@MainActivity, indicatorTitles.size)
        }

        //配合底部 tab 和 viewpager2
        ViewPager2Delegate.install(binding.content.pager, binding.content.indicator, forceSmoothScroll = true)

        // 底部（tab）
        for (i in indicatorTitles.indices) {
            ItemTabBinding.inflate(layoutInflater).apply {
                icon.setImageResource(indicatorIcons[i])
                content.setText(indicatorTitles[i])
                binding.content.indicator.addView(root) // root 是 item_tab.xml 的根布局
            }
        }

        viewModel.loadSplashAd()

    }

    override fun initListeners() {
        super.initListeners()

        //关闭应用点击
        binding.closeApp.setOnClickListener {
            SuperProcessUtil.killApp()
        }

        //用户容器点击
        binding.userContainer.setOnClickListener {
            closeDrawer()
            if (PreferenceUtil.isLogin()) {
                startActivityExtraId(UserDetailActivity::class.java, PreferenceUtil.getUserId())
            } else {
                startActivity(LoginHomeActivity::class.java)
            }
        }

        //退出登录点击
        binding.primary.setOnClickListener {
            SuperDialog.newInstance(supportFragmentManager)
                .setTitleRes(R.string.confirm_logout)
                .setOnClickListener {
                    AppContext.instance.logout()
                    showNotLogin()
                    closeDrawer()
                }.show()
        }
    }

    override fun onResume() {
        super.onResume()
        showUserInfo()
    }

    private fun processAdClick(data: Ad) {
        if (data.uri!!.startsWith("http")) {
            WebActivity.start(hostActivity, data.uri!!)
        } else {
            try {
                //打开应用
                val intent = Intent(Intent.ACTION_VIEW)
                val uri = Uri.parse(data.uri)
                //例如：打开我们在腾讯课程上的仿微信项目课程详情页面
//            val uri = Uri.parse("tencentedu://openpage/coursedetail?courseid=4875119&termid=103425768&taid=11008662607906617&fromWeb=1&sessionPath=165013705913519225082472#");
//            val uri = Uri.parse("http://www.ixuea.com/")

                intent.data = uri
                startActivity(intent)
            } catch (e: ActivityNotFoundException) {
                //没有安装对应的应用
                R.string.not_found_activity.shortToast()
            }
        }
    }

    private fun showUserInfo() {
        if (PreferenceUtil.isLogin()) {
            //已经登录了

            //获取用户信息
            viewModel.loadUserData()
            binding.primary.show()
        } else {
            showNotLogin()
        }
    }

    private fun showUserData(data: User) {
        //显示头像
        ImageUtil.showAvatar(binding.avatar, data.icon)

        //显示昵称
        binding.nickname.text = data.nickname
    }

    /**
     * 显示未登录状态
     */
    private fun showNotLogin() {
        binding.nickname.setText(R.string.login_or_register)
        binding.avatar.setImageResource(R.drawable.default_avatar)
        binding.primary.hide()
    }

    fun openDrawer() {
        binding.drawer.openDrawer(GravityCompat.START)
    }

    fun closeDrawer() {
        binding.drawer.closeDrawer(GravityCompat.START)
    }


}